package com.yang.modules.common.filter;


import com.yang.common.core.util.MdcUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 生成日志id过滤器
 * (未被spring管理的类中，不能用注入的方式获取实例，否则会空指针)
 * @author Billyang
 * @date 2024/9/14 14:52
 */
@Slf4j
public class TraceIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String traceId = request.getHeader(MdcUtil.UNIQUE_KEY);
            MdcUtil.put(traceId);
            log.info("traceId is :{}", traceId);
            filterChain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }
}
